<template>
  <div class="settings-container">
    <CustomScrollbar>
      <div class="settings-content">
        <div class="settings-header">
          <h1>设置</h1>
        </div>

        <!-- 账号设置 -->
        <section class="settings-section">
          <h2>账号</h2>

          <div class="setting-item">
            <div class="setting-info">
              <label>个人资料</label>
              <p>编辑您的姓名、用户名和邮箱地址</p>
            </div>
            <button @click="editProfile" class="setting-btn">
              编辑
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M3,17.25V21H6.75L17.81,9.94L14.06,6.19L3,17.25ZM20.71,7.04C21.1,6.65 21.1,6.02 20.71,5.63L18.37,3.29C17.98,2.9 17.35,2.9 16.96,3.29L15.13,5.12L18.88,8.87L20.71,7.04Z" />
              </svg>
            </button>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <label>修改密码</label>
              <p>更改您的登录密码，需要手机验证码确认</p>
            </div>
            <button @click="changePassword" class="setting-btn" :disabled="!userPhone">
              {{ userPhone ? '修改' : '需绑定手机号' }}
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M22,18V22H18V19H15V16H12L9.74,13.74C9.19,13.91 8.61,14 8,14A6,6 0 0,1 2,8A6,6 0 0,1 8,2A6,6 0 0,1 14,8C14,8.61 13.91,9.19 13.74,9.74L22,18M7,5A1,1 0 0,0 6,6A1,1 0 0,0 7,7A1,1 0 0,0 8,6A1,1 0 0,0 7,5Z" />
              </svg>
            </button>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <label>手机号绑定</label>
              <p v-if="!userPhone">绑定或更换您的手机号码</p>
              <p v-else class="phone-bound">
                <span class="phone-number">已绑定手机号：{{ formatPhone(userPhone) }}</span>
              </p>
            </div>
            <button @click="bindPhone" class="setting-btn">
              {{ userPhone ? '更换' : '绑定' }}
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M6.62,10.79C8.06,13.62 10.38,15.94 13.21,17.38L15.41,15.18C15.69,14.9 16.08,14.82 16.43,14.93C17.55,15.3 18.75,15.5 20,15.5A1,1 0 0,1 21,16.5V20A1,1 0 0,1 20,21A17,17 0 0,1 3,4A1,1 0 0,1 4,3H7.5A1,1 0 0,1 8.5,4C8.5,5.25 8.7,6.45 9.07,7.57C9.18,7.92 9.1,8.31 8.82,8.59L6.62,10.79Z" />
              </svg>
            </button>
          </div>
        </section>

        <!-- 设置 -->
        <section class="settings-section">
          <h2>设置</h2>

          <div class="setting-item">
            <div class="setting-info">
              <label>退出账户</label>
              <p>退出当前账户，下次需要重新登录</p>
            </div>
            <button @click="logout" class="setting-btn logout-action">
              退出
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M17,7L15.59,8.41L18.17,11H8V13H18.17L15.59,15.59L17,17L22,12L17,7M4,5H12V3H4A2,2 0 0,0 2,5V19A2,2 0 0,0 4,21H12V19H4V5Z" />
              </svg>
            </button>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <label>注销账户</label>
              <p>永久删除您的账户和所有相关数据</p>
            </div>
            <button @click="deleteAccount" class="setting-btn delete-action">
              注销
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z" />
              </svg>
            </button>
          </div>
        </section>
      </div>
    </CustomScrollbar>








  </div>
</template>

<script>
import CustomScrollbar from '@/components/CustomScrollbar.vue'

export default {
  name: 'SettingsView',
  components: {
    CustomScrollbar
  },
  data() {
    return {
      // 用户信息
      userPhone: ''
    }
  },

  computed: {
    username() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      return userInfo.username || localStorage.getItem('username') || '';
    },
    userEmail() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      return userInfo.email || localStorage.getItem('userEmail') || '';
    }
  },

  mounted() {
    this.loadUserInfo();
  },

  methods: {
    async loadUserInfo() {
      // 检查用户登录状态
      const userToken = localStorage.getItem('userToken');
      const userExpiry = localStorage.getItem('userTokenExpiry');
      
      if (!userToken || !userExpiry || Date.now() > parseInt(userExpiry)) {
        console.log('用户未登录或token过期，跳转到登录页');
        this.$router.push('/users/login');
        return;
      }
      
      try {
        // 从后端获取最新的用户信息
        const response = await this.$http.get('/api/users/profile', {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        if (response.success && response.user) {
          // 使用后端返回的用户信息
          const userInfo = response.user;
          // 只有当phone字段存在且不为空时才设置userPhone
          this.userPhone = userInfo.phone || '';
          
          console.log('从后端加载用户信息:', {
            username: userInfo.username,
            email: userInfo.email,
            phone: this.userPhone
          });
        } else {
          // 如果后端请求失败，使用localStorage作为备份
          // 注册用户没有绑定手机号，所以不从localStorage获取可能错误的手机号
          this.userPhone = '';
          
          console.log('从localStorage加载用户信息');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 请求失败时，不设置手机号
        this.userPhone = '';
      }
    },

    formatPhone(phone) {
      // 格式化手机号显示，例如：138****1234
      if (!phone || phone.length !== 11) return phone;
      return phone.substring(0, 3) + '****' + phone.substring(7);
    },

    editProfile() {
      if (!this.userPhone) {
        this.$root.showToast('请先绑定手机号', 'warning');
        return;
      }
      // 使用全局弹窗系统
      this.$root.showGlobalModal('ProfileEditModal', {
        userPhone: this.userPhone,
        username: this.username,
        email: this.userEmail
      });
    },



    changePassword() {
      if (!this.userPhone) {
        this.$root.showToast('请先绑定手机号', 'warning');
        return;
      }
      // 使用全局弹窗系统
      this.$root.showGlobalModal('PasswordChangeModal', {
        userPhone: this.userPhone
      });
    },


    async savePassword() {
      // 验证表单
      if (!this.passwordForm.newPassword) {
        this.$root.showToast('请输入新密码', 'warning');
        return;
      }
      if (this.passwordForm.newPassword.length < 6) {
        this.$root.showToast('新密码至少需要6位', 'warning');
        return;
      }
      if (!this.passwordForm.confirmPassword) {
        this.$root.showToast('请输入确认密码', 'warning');
        return;
      }
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.$root.showToast('两次输入的密码不一致', 'warning');
        return;
      }

      try {
        // 准备请求数据
        const passwordData = {
          verificationCode: this.passwordForm.verifyCode,
          newPassword: this.passwordForm.newPassword,
          confirmPassword: this.passwordForm.confirmPassword
        };

        // 获取用户token
        const userToken = localStorage.getItem('userToken');
        const userExpiry = localStorage.getItem('userTokenExpiry');
        if (!userToken || !userExpiry || Date.now() > parseInt(userExpiry)) {
          this.$root.showToast('登录已过期，请重新登录', 'error');
          this.$router.push('/users/login');
          return;
        }

        // 调用后端API修改密码
        const response = await this.$http.post('/api/users/change-password', passwordData, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        if (response.success) {
          this.$root.showToast('密码修改成功', 'success');
          this.showPasswordDialog = false;
        } else {
          this.$root.showToast(response.message || '修改密码失败', 'error');
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        const errorMessage = error.response?.data?.message || '修改密码失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },

    bindPhone() {
      // 使用全局弹窗系统
      this.$root.showGlobalModal('PhoneBindModal', {
        userPhone: this.userPhone
      });
    },

    async sendCode() {
      if (this.codeCountdown > 0) return;

      const phonePattern = /^1[3-9]\d{9}$/;
      if (!phonePattern.test(this.phoneForm.phone)) {
        this.$root.showToast('请输入正确的手机号码', 'warning');
        return;
      }

      try {
        // 调用后端API发送验证码
        const response = await this.$http.post('/api/users/send-code', null, {
          params: { phone: this.phoneForm.phone }
        });

        if (response.success) {
          this.showVerificationCode = true;
          this.phoneForm.code = '';

          // 获取验证码（开发环境显示）
          if (response.verificationCode) {
            this.phoneGeneratedCode = response.verificationCode;
          }

          this.codeCountdown = 60;
          const timer = setInterval(() => {
            this.codeCountdown--;
            if (this.codeCountdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);

          this.$root.showToast('验证码已发送', 'success');
        } else {
          this.$root.showToast(response.message || '发送验证码失败', 'error');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        const errorMessage = error.response?.data?.message || '发送验证码失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },

    async bindPhoneNumber() {
      if (!this.phoneForm.code || this.phoneForm.code.length !== 4) {
        this.$root.showToast('请输入4位验证码', 'warning');
        return;
      }

      try {
        // 准备请求数据
        const bindData = {
          phone: this.phoneForm.phone,
          verificationCode: this.phoneForm.code
        };

        // 获取用户token
        const userToken = localStorage.getItem('userToken');
        const userExpiry = localStorage.getItem('userTokenExpiry');
        if (!userToken || !userExpiry || Date.now() > parseInt(userExpiry)) {
          this.$root.showToast('登录已过期，请重新登录', 'error');
          this.$router.push('/users/login');
          return;
        }

        // 调用后端API绑定手机号
        const response = await this.$http.post('/api/users/bind-phone', bindData, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        if (response.success) {
          // 更新本地存储
          this.userPhone = this.phoneForm.phone;
          // 更新用户信息到localStorage
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          userInfo.phone = this.phoneForm.phone;
          localStorage.setItem('userInfo', JSON.stringify(userInfo));

          this.$root.showToast('手机号绑定成功', 'success');
          this.showPhoneDialog = false;

          // 刷新登录状态
          if (this.$root.refreshLoginStatus) {
            this.$root.refreshLoginStatus();
          }
        } else {
          this.$root.showToast(response.message || '绑定失败', 'error');
        }
      } catch (error) {
        console.error('绑定手机号失败:', error);
        const errorMessage = error.response?.data?.message || '绑定失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },

    logout() {
      // 使用全局弹窗系统
      this.$root.showGlobalModal('LogoutConfirmModal');
    },

    deleteAccount() {
      if (!this.userPhone) {
        this.$root.showToast('请先绑定手机号', 'warning');
        return;
      }
      // 使用全局弹窗系统
      this.$root.showGlobalModal('DeleteAccountModal', {
        userPhone: this.userPhone
      });
    },

    async sendDeleteVerifyCode() {
      if (this.deleteCodeCountdown > 0) return;

      try {
        // 调用后端API发送验证码
        const response = await this.$http.post('/api/users/send-code', null, {
          params: { phone: this.deleteVerifyPhone }
        });

        if (response.success) {
          // 获取验证码（开发环境显示）
          if (response.verificationCode) {
            this.deleteGeneratedCode = response.verificationCode;
          }

          this.deleteCodeCountdown = 60;
          const timer = setInterval(() => {
            this.deleteCodeCountdown--;
            if (this.deleteCodeCountdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);

          this.$root.showToast('验证码已发送', 'success');
        } else {
          this.$root.showToast(response.message || '发送验证码失败', 'error');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        const errorMessage = error.response?.data?.message || '发送验证码失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    },

    async confirmDeleteAccount() {
      if (!this.deleteForm.password) {
        this.$root.showToast('请输入密码', 'warning');
        return;
      }
      if (!this.deleteForm.verifyCode || this.deleteForm.verifyCode.length !== 4) {
        this.$root.showToast('请输入4位验证码', 'warning');
        return;
      }

      try {
        // 准备请求数据
        const deleteData = {
          password: this.deleteForm.password,
          verificationCode: this.deleteForm.verifyCode
        };

        // 获取用户token
        const userToken = localStorage.getItem('userToken');
        const userExpiry = localStorage.getItem('userTokenExpiry');
        if (!userToken || !userExpiry || Date.now() > parseInt(userExpiry)) {
          this.$root.showToast('登录已过期，请重新登录', 'error');
          this.$router.push('/users/login');
          return;
        }

        // 调用后端API注销账户
        const response = await this.$http.post('/api/users/delete-account', deleteData, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });

        if (response.success) {
          // 清除所有本地数据
          localStorage.clear();

          this.$root.showToast('账户已注销', 'success');
          this.showDeleteDialog = false;

          // 刷新登录状态
          if (this.$root.refreshLoginStatus) {
            this.$root.refreshLoginStatus();
          }

          // 跳转到首页
          this.$router.push('/');
        } else {
          this.$root.showToast(response.message || '注销失败', 'error');
        }
      } catch (error) {
        console.error('注销账户失败:', error);
        const errorMessage = error.response?.data?.message || '注销失败，请重试';
        this.$root.showToast(errorMessage, 'error');
      }
    }
  }
}
</script>

<style scoped>
.settings-container {
  width: 100%;
  height: 100%;
  background: #121212;
  color: white;
}

.settings-content {
  padding: 64px 32px 32px;
  max-width: 800px;
  margin: 0 auto;
}

.settings-header {
  margin-bottom: 48px;
}

.settings-header h1 {
  font-size: 48px;
  font-weight: 900;
  margin: 0;
  color: white;
}

.settings-section {
  margin-bottom: 48px;
}

.settings-section h2 {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 24px 0;
  color: white;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
  border-bottom: 1px solid #282828;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info {
  flex: 1;
}

.setting-info label {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: white;
  margin-bottom: 4px;
}

.setting-info p {
  font-size: 14px;
  color: #b3b3b3;
  margin: 0;
  line-height: 1.4;
}

.phone-bound .phone-number {
  font-weight: 600;
  transition: all 0.3s ease;
  cursor: pointer;
}

.phone-bound .phone-number:hover {
  color: #1db954 !important;
}

.setting-btn {
  background: transparent;
  border: 1px solid #727272;
  color: white;
  padding: 10px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  min-width: 80px;
  justify-content: center;
}

.setting-btn:hover {
  border-color: white;
  transform: scale(1.02);
}

.logout-action {
  border-color: #1db954;
  color: #1db954;
}

.logout-action:hover {
  background: #1db954;
  color: black;
}

.delete-action {
  border-color: #e22134;
  color: #e22134;
}

.delete-action:hover {
  background: #e22134;
  color: white;
}

.setting-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  border-color: #535353;
  color: #535353;
}

.verify-notice {
  background: rgba(29, 185, 84, 0.1);
  border: 1px solid #1db954;
  border-radius: 4px;
  padding: 12px;
  margin-top: 16px;
  color: #1db954;
  font-size: 14px;
  text-align: center;
}



@media (max-width: 768px) {
  .settings-content {
    padding: 32px 16px;
  }

  .settings-header h1 {
    font-size: 32px;
  }

  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .setting-btn {
    align-self: flex-end;
  }
}
</style>